package com.vise.bledemo.jky;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.vise.baseble.ViseBle;
import com.vise.baseble.callback.scan.IScanCallback;
import com.vise.baseble.callback.scan.ScanCallback;
import com.vise.baseble.common.PropertyType;
import com.vise.baseble.model.BluetoothLeDevice;
import com.vise.baseble.model.BluetoothLeDeviceStore;
import com.vise.bledemo.R;
import com.vise.bledemo.common.BluetoothDeviceManager;
import com.vise.bledemo.common.ToastUtil;
import com.vise.bledemo.event.ConnectEvent;
import com.vise.bledemo.utils.ConvertUtil;
import com.vise.log.ViseLog;
import com.vise.log.inner.LogcatTree;
import com.vise.xsnow.event.BusManager;
import com.vise.xsnow.event.Subscribe;

import java.util.HashMap;
import java.util.UUID;

public class BTQRTestActivity extends Activity {


    public static String BTName = "";
    // 本地蓝牙适配器
    private BluetoothAdapter mBluetoothAdapter;

    private ProgressDialog progressDialog;
    private static String cmd = "";

    public static void startLHYtest(Activity activity, String checktype) {
        cmd = "LKO";
        BTName = checktype;
        activity.startActivity(new Intent(activity, BTQRTestActivity.class));
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        BTName = "NBeeNET_4831B7341B60";
        setContentView(R.layout.activity_btqrtest);
        initView();
        setTitle("选择蓝牙");
    }

    @Subscribe
    public void showConnectedDevice(ConnectEvent event) {
        if (event != null) {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            if (event.isSuccess()) {
                ToastUtil.showToast(BTQRTestActivity.this, "设备连接成功");
                initBT();
            } else {
                if (event.isDisconnected()) {
                    ToastUtil.showToast(BTQRTestActivity.this, "设备已断开!");
                } else {
                    ToastUtil.showToast(BTQRTestActivity.this, "设备连接失败!");

                }
            }
        }
    }

    public void initBT() {
        if (mDevice != null && BluetoothDeviceManager.getInstance().isConnected(mDevice)) {
            ToastUtil.showToast(this, "蓝牙链接成功 执行写入服务！！！");
            BluetoothDeviceManager.getInstance().bindChannel(mDevice, PropertyType.PROPERTY_WRITE,
                    UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"),
                    UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"), null);
            BluetoothDeviceManager.getInstance().write(mDevice, ConvertUtil.hexStr2Bytes(ConvertUtil.str2HexStr(cmd)));
            ToastUtil.showToast(BTQRTestActivity.this, "设备操作完毕");
            finish();
        } else {
            ToastUtil.showToast(this, "没有选择蓝牙设备！！！");
        }
    }


    @Override
    protected void onDestroy() {
        BusManager.getBus().unregister(this);
        super.onDestroy();
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        BluetoothDeviceManager.getInstance().disconnect(mDevice);
    }

    //创建一个Handle
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            //判断：根据Message的标识判断消息
            if (msg.what == 0) {
                if (isFind == false) {
                    Toast.makeText(BTQRTestActivity.this, "未找到对应的设备或设备已关闭，请检查并确认设备是否开启并在手机附近", Toast.LENGTH_SHORT).show();
                }
                finish();
            }

        }
    };


    private void initView() {

        ViseLog.getLogConfig().configAllowLog(true);//配置日志信息
        ViseLog.plant(new LogcatTree());//添加Logcat打印信息
        BusManager.getBus().register(this);
        // 获取本地蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 判断手机是否支持蓝牙
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
            finish();
        }

        // 判断是否打开蓝牙
        if (!mBluetoothAdapter.isEnabled()) {
            // 弹出对话框提示用户是后打开
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, 1);
            finish();
        } else {
            progressDialog = ProgressDialog.show(this, "", "正在连接请稍后");
            ViseBle.getInstance().startScan(periodScanCallback);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    progressDialog.dismiss();
                    ViseBle.getInstance().stopScan(periodScanCallback);
                }
            }, 5000);
        }
        mHandler.sendEmptyMessageDelayed(0, 5000);
    }

    boolean isFind = false;
    BluetoothLeDevice mDevice;
    HashMap<String, String> ker = new HashMap<>();
    private ScanCallback periodScanCallback = new ScanCallback(new IScanCallback() {
        @Override
        public void onDeviceFound(final BluetoothLeDevice bluetoothLeDevice) {
            ViseLog.i("Founded Scan Device:" + bluetoothLeDevice);
            if (!TextUtils.isEmpty(bluetoothLeDevice.getDevice().getName()) && !ker.containsKey(bluetoothLeDevice.getAddress())) {
                ker.put(bluetoothLeDevice.getAddress(), bluetoothLeDevice.getName());
                if (BTName.equals(bluetoothLeDevice.getDevice().getName())) {
                    isFind = true;
                    BTQRTestActivity.this.mDevice = bluetoothLeDevice;
                    Toast.makeText(BTQRTestActivity.this, "找到要连接设备", Toast.LENGTH_SHORT).show();
                    ViseBle.getInstance().stopScan(periodScanCallback);
                    mHandler.removeCallbacksAndMessages(null);
                    if (!BluetoothDeviceManager.getInstance().isConnected(bluetoothLeDevice)) {
                        BluetoothDeviceManager.getInstance().connect(bluetoothLeDevice);
                    } else {
                        ToastUtil.showToast(BTQRTestActivity.this, "已经连接成功");
                    }
                }
            }
        }

        @Override
        public void onScanFinish(BluetoothLeDeviceStore bluetoothLeDeviceStore) {
            ViseLog.i("scan finish " + bluetoothLeDeviceStore);
            finish();
        }

        @Override
        public void onScanTimeout() {
            ViseLog.i("scan timeout");
            finish();
        }

    });

}